package yxy.game.pm2.command.union.war;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.UnionWarMessage;
import yxy.game.pm2.module.union.UnionBean;
import yxy.game.pm2.module.union.UnionHandle;
import yxy.game.pm2.module.union.UnionHandle.UnionPlayerEntry;
import yxy.game.pm2.module.union.war.UnionWarUnionModule;

/** 联盟战 联盟战战果宝箱 */
@MessageType(proto = Command.UnionWarBox, classtype = UnionWarMessage.UnionWarBoxRequest.class)
public class CMD_UnionWarBox extends Command<UnionWarMessage.UnionWarBoxRequest> {

	@Override
	public void execute(MessageSource messageSource, UnionWarMessage.UnionWarBoxRequest request) {
		String playerCode = messageSource.getTag();

		UnionWarMessage.UnionWarBoxResponse.Builder response = UnionWarMessage.UnionWarBoxResponse.newBuilder();

		// 检查是否已经有联盟
		UnionPlayerEntry entry = new UnionPlayerEntry(playerCode);
		{
			Result result = new UnionHandle().checkPlayerUnion(entry);
			if (!result.equals(Result.UnionIn)) {
				send(messageSource, response, result);
				return;
			}
		}
		UnionBean union = entry.getUnionBean();
		UnionWarUnionModule unionWarUnionModule = UnionWarUnionModule.get(union.getCode());
		if (unionWarUnionModule == null) {
			send(messageSource, response, Result.Success);
			return;
		}

		int i = 0;
		for (yxy.game.pm2.module.union.war.UnionWarBox box : unionWarUnionModule.getBoxes()) {
			UnionWarMessage.UnionWarBox.Builder builder = UnionWarMessage.UnionWarBox.newBuilder();
			builder.setId(i++);
			if (box.getWinner() != null) {
				builder.setReward(box.getReward().getNumber());
				builder.setName(box.getWinner());
			}
			response.addBox(builder);
		}

		send(messageSource, response, Result.Success);
	}

	private void send(MessageSource messageSource, UnionWarMessage.UnionWarBoxResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}